package com.onegene.pdf.service.impl;

import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.onegene.pdf.component.config.CommonParam;
import com.onegene.pdf.component.entity.EarlyReportBean;
import com.onegene.pdf.component.entity.LogoImage;
import com.onegene.pdf.component.entity.PrintReportBean;
import com.onegene.pdf.component.entity.Result;
import com.onegene.pdf.service.CommonService;
import com.onegene.pdf.entity.Sample;
import com.onegene.pdf.entity.SampleResult;
import com.onegene.pdf.mapper.LogoImageMapper;
import com.onegene.pdf.mapper.SampleMapper;
import com.onegene.pdf.util.Precondition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: laoliangliang
 * @description:
 * @create: 2020/7/27 15:58
 **/
@Service
@Slf4j
public class CommonServiceImpl implements CommonService {

    @Autowired
    private LogoImageMapper logoImageMapper;

    @Autowired
    private SampleMapper sampleMapper;

    @Autowired
    private CommonParam commonParam;

    @Autowired
    private Environment environment;

    @Override
    /**
     * @param token
     * @param uuid
     * @param type  报告类型 0-易感  1-用药 2-简化版
     * @return
     */
    public PrintReportBean getGeneReportBean(String token, String uuid, Integer type) {
        Map<String, Object> params = new HashMap<>(1);
        String body = null;
        int version = 1;
        if (type == 0) {
            // version 1-标准版（去除体检建议和预防建议） 2-完整版
            version = 1;
        } else if (type == 2) {
            version = 2;
        }
        int tryCount = 0;
        Result<PrintReportBean> reportBeanResult = null;
        while (tryCount < 3) {
            if (type == 1) {
                log.info("commonParam.adultDrugUrl:{}", commonParam.adultDrugUrl);
                body = HttpUtil.post(commonParam.adultDrugUrl + "?access_token=" + token + "&uuid=" + uuid, params);
            } else if(type == 2 || type == 0) {
                log.info("commonParam.geneUrl:{}", commonParam.geneUrl);
                body = HttpUtil.post(commonParam.geneUrl + "?access_token=" + token + "&uuid=" + uuid + "&version=" + version, params);
            }else if(type == 3){
                log.info("commonParam.geneUrl:{}", commonParam.earlyUrl);
                body = HttpUtil.post(commonParam.earlyUrl + "?access_token=" + token + "&uuid=" + uuid, params);
            }
            Precondition.checkNotNull(body, "返回结果为空，可能type类型不存在");
            if (body.contains("access_token错误")) {
                Precondition.throwDataException(body);
            }
            try {
                reportBeanResult = JSON.parseObject(body, new TypeReference<Result<PrintReportBean>>() {
                });
            } catch (JSONException e) {
                log.error("C端数据解析异常：" + body, e);
                tryCount++;
                if (tryCount == 3) {
                    MailUtil.send("laoliangliang1911@1gene.com.cn", "生成报告出错", "<h1>UUID:" + uuid + "报告未成功生成（" + environment.getActiveProfiles()[0] + "）</h1>", true);
                    throw e;
                }
                continue;
            }
            break;
        }
        if (reportBeanResult == null) {
            return null;
        }
        PrintReportBean data = reportBeanResult.getData();
        if (data == null) {
            return null;
        }
        return data;
    }

    @Override
    public EarlyReportBean getEarlyReportBean(String token, String uuid, Integer type) {
        Map<String, Object> params = new HashMap<>(1);
        String body = null;
        int tryCount = 0;
        Result<EarlyReportBean> reportBeanResult = null;
        while (tryCount < 3) {
            if(type == 3){
                log.info("commonParam.geneUrl:{}", commonParam.earlyUrl);
                body = HttpUtil.post(commonParam.earlyUrl + "?access_token=" + token + "&uuid=" + uuid, params);
            }
            Precondition.checkNotNull(body, "返回结果为空，可能type类型不存在");
            if (body.contains("access_token错误")) {
                Precondition.throwDataException(body);
            }
            try {
                reportBeanResult = JSON.parseObject(body, new TypeReference<Result<EarlyReportBean>>() {
                });
            } catch (JSONException e) {
                log.error("C端数据解析异常：" + body, e);
                tryCount++;
                if (tryCount == 3) {
                    MailUtil.send("laoliangliang1911@1gene.com.cn", "生成报告出错", "<h1>UUID:" + uuid + "报告未成功生成（" + environment.getActiveProfiles()[0] + "）</h1>", true);
                    throw e;
                }
                continue;
            }
            break;
        }
        if (reportBeanResult == null) {
            return null;
        }
        EarlyReportBean data = reportBeanResult.getData();
        if (data == null) {
            return null;
        }
        return data;
    }

    @Override
    public LogoImage getLogoImageUrl(String logoCode) {
        if (!StringUtils.isEmpty(logoCode)) {
            LogoImage logoImageQuery = new LogoImage();
            logoImageQuery.setCode(logoCode);
            LogoImage logoImage = logoImageMapper.selectOne(logoImageQuery);
            if (logoImage != null) {
                return logoImage;
            }
        }
        return null;
    }

    @Override
    public SampleResult getSampleResult(String uuid) {
        Sample sampleQuery = new Sample();
        sampleQuery.setUuid(uuid);
        return sampleMapper.selectSampleResult(sampleQuery);
    }
}
